package org.jeecg.modules.scene.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.device.entity.DeviceInstance;
import org.jeecg.modules.device.entity.DeviceModel;
import com.zhouwr.common.enums.DeviceInstanceState;
import org.jeecg.modules.device.service.IDeviceInstanceService;
import org.jeecg.modules.device.service.IDeviceModelService;
import org.jeecg.modules.scene.entity.Scene;
import org.jeecg.modules.scene.entity.SceneScheme;
import org.jeecg.modules.scene.service.ISceneSchemeService;
import org.jeecg.modules.scene.service.ISceneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description: 场景管理
 * @Author: zhouwr
 * @Date: 2020-06-04
 * @Version: V1.0
 */
@Slf4j
@RestController
@Api(tags = "场景部署")
@RequestMapping("/scene/deploy")
public class SceneDeployController {
    @Autowired
    private ISceneService sceneService;
    @Autowired
    private ISceneSchemeService sceneSchemeService;
    @Autowired
    private IDeviceInstanceService instanceService;
    @Autowired
    private IDeviceModelService deviceModelService;


    @RequestMapping("/toEditor")
    public ModelAndView toEditor(String token, ModelAndView modelAndView) {
        final String username = JwtUtil.getUsername(token);
        log.info(username);

        modelAndView.setViewName("deploy");
        modelAndView.addObject("token", token);
        modelAndView.addObject("username", username);
        return modelAndView;
    }

    @AutoLog(value = "场景管理-获取当前登录机构下的场景配置信息")
    @ApiOperation(value = "场景管理-获取场景配置信息", notes = "场景管理-获取当前登录机构下的场景配置信息")
    @GetMapping(value = "/getDeployConfig")
    public Result<?> getDeployConfig(@RequestParam(name = "id", required = false) String id, HttpServletRequest req) {
        Scene scene = new Scene();
        log.info(">>>>>>> sceneId: {}", id);
        if (oConvertUtils.isEmpty(id) || "undefined".equals(id)) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            log.info("当前用户所属组织：{}", sysUser);

            //校验Token有效性
            String token = req.getParameter("token");

            if (sysUser == null) {
                return Result.error("获取用户登录信息失败");
            }
            List<Scene> list = sceneService.lambdaQuery().eq(Scene::getSysOrgCode, sysUser.getOrgCode()).list();
            if (list != null && list.size() > 0) {
                scene = list.get(0);
            } else {
                return Result.error("未找到当前登录用户所属场景数据");
            }
        } else {
            scene = sceneService.getById(id);
            if (scene == null) {
                return Result.error("未找到id为：" + id + "的场景");
            }
        }

        // 设备实例
        List<DeviceInstance> deviceInstanceList = instanceService.lambdaQuery()
                .eq(DeviceInstance::getSceneBy, scene.getId())
                .ne(DeviceInstance::getStatus, DeviceInstanceState.NOT_ACTIVE)
                .list();

        JSONArray deviceInstanceJsonArray = new JSONArray();
        deviceInstanceList.forEach(instance -> {
            JSONObject deviceInstanceObject = instance.toJSON();
            String sceneSchemeBy = deviceInstanceObject.getString("sceneSchemeBy");
            SceneScheme sceneScheme = sceneSchemeService.getById(sceneSchemeBy);
            deviceInstanceObject.put("sceneSchemeName", sceneScheme != null ? sceneScheme.getName() : sceneSchemeBy);

            // 设备模型
            DeviceModel model = deviceModelService.getById(instance.getModelBy());
            deviceInstanceObject.put("modelFiles", model.getThreeModelFile());
            deviceInstanceObject.put("type", model.getType());
            deviceInstanceJsonArray.add(deviceInstanceObject);
        });

        JSONObject sceneObj = (JSONObject) JSONObject.toJSON(scene);
        sceneObj.put("type", "scene");
        sceneObj.put("deviceInstances", deviceInstanceJsonArray);
        return Result.ok(sceneObj);
    }
}
